package com.ryan.msm.controller;

import com.ryan.msm.sevice.MsmService;
import com.ryan.msm.utils.RandomUtil;
import com.ryan.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/sendMsm/{phoneNumber}")
    public R sendMsm(@PathVariable String phoneNumber){
        //首先从redis缓存中获取验证码
        String code = redisTemplate.opsForValue().get(phoneNumber);
        //如果code有值表明redis中存的验证码还有效
        if(!StringUtils.isEmpty(code)){
            return R.ok().message("验证码还在有效时间内");
        }
        //如果为空，表明验证码过期了，需要重新发送
        code = RandomUtil.getFourBitRandom();
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        Boolean isSend = msmService.sendMsm(map, phoneNumber);
        if (isSend){
            //发送成功
            redisTemplate.opsForValue().set(phoneNumber, code, 5, TimeUnit.MINUTES);
            return R.ok().message("验证码已发送");
        }else {
            return R.error().message("验证码发送失败");
        }
    }
}
